import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:wowhy/service_locator.dart';

import 'package:wowhy/services/admin_user_service.dart';
import 'package:wowhy/models/paged_result.dart';
import 'package:wowhy/models/admin_user_info.dart';
import 'package:wowhy/services/navigate_service.dart';

import '../admin_user_list_page/admin_user_item_component/state.dart';

import 'action.dart';
import 'state.dart';

Effect<AdminUserListState> buildEffect() {
  return combineEffects(<Object, Effect<AdminUserListState>>{
    Lifecycle.initState: _init,
    AdminUserListAction.onSearch: _onSearch,
    AdminUserListAction.onRefresh: _onRefresh,
    AdminUserListAction.onFetch: _onFetch,
    AdminUserListAction.onAdd: _onAdd,
  });
}

void _init(Action action, Context<AdminUserListState> ctx) async {
  ctx.dispatch(AdminUserListActionCreator.onRefresh());
}

void _onSearch(Action action, Context<AdminUserListState> ctx) async {
  final dynamic query = await getIt<NavigateService>().pushNamed(
    'search',
    arguments: {
      'query': ctx.state.query,
    },
  );

  if (query is String) {
    await ctx.dispatch(AdminUserListActionCreator.search(query));
    await ctx.dispatch(AdminUserListActionCreator.onRefresh());
  }
}

void _onRefresh(Action action, Context<AdminUserListState> ctx) async {
  try {
    ctx.state.refreshController.requestRefresh();
    PagedResult<AdminUserInfo> pagedResult =
        await AdminUserService.instance.pagination(
      page: 1,
      limit: ctx.state.pageSize,
      query: ctx.state.query,
    );
    ctx.dispatch(AdminUserListActionCreator.refresh(AdminUserListState(
      list: pagedResult.items
          .map((item) => AdminUserItemState.fromModel(item))
          .toList(),
      total: pagedResult.total,
      page: 1,
    )));
  } catch (ex) {
    ctx.state.refreshController.refreshFailed();
  }
}

void _onFetch(Action action, Context<AdminUserListState> ctx) async {
  try {
    final page = ctx.state.page + 1;
    PagedResult<AdminUserInfo> pagedResult =
        await AdminUserService.instance.pagination(
      page: page,
      limit: ctx.state.pageSize,
      query: ctx.state.query,
    );
    ctx.dispatch(AdminUserListActionCreator.fetch(AdminUserListState(
      list: pagedResult.items
          .map((item) => AdminUserItemState.fromModel(item))
          .toList(),
      total: pagedResult.total,
      page: page,
    )));
  } catch (ex) {
    ctx.state.refreshController.refreshFailed();
  }
}

void _onAdd(Action action, Context<AdminUserListState> ctx) async {
  dynamic result = await getIt<NavigateService>().pushNamed('admin_user_edit');
  if (result != null) {
    await ctx.dispatch(AdminUserListActionCreator.add(result));
  }
}
